package com.satan.novel.user.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.satan.novel.common.auth.JwtUtils;
import com.satan.novel.common.auth.UserHolder;
import com.satan.novel.common.constant.ErrorCodeEnum;
import com.satan.novel.common.constant.SystemConfigConsts;
import com.satan.novel.config.exception.BusinessException;
import com.satan.novel.user.dto.UserInfoDto;
import com.satan.novel.user.manager.cache.UserInfoCacheManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * @ClassName AuthInterceptor
 * @Description TODO
 * @date 2024/1/17 22:06
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    private final ObjectMapper objectMapper;
    private final UserInfoCacheManager userInfoCacheManager;


    @Override
    @SuppressWarnings("NullableProblems")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录jwt
        String token = request.getHeader(SystemConfigConsts.HTTP_AUTH_HEADER_NAME);
        //开始认证
        if (!StringUtils.hasText(token)) {
            //token为空
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        Long userId = JwtUtils.parseToken(token, SystemConfigConsts.NOVEL_FRONT_KEY);
        if (userId == null) {
            //token无效
            throw new BusinessException(ErrorCodeEnum.USER_LOGIN_EXPIRED);
        }
        UserInfoDto userInfo = userInfoCacheManager.getUser(userId);
        if (Objects.isNull(userInfo)) {
            // 用户不存在
            throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_NOT_EXIST);
        }
        // 设置 userId 到当前线程
        UserHolder.setUserId(userId);
        return HandlerInterceptor.super.preHandle(request, response, handler);

    }

    @Override
    @SuppressWarnings("NullableProblems")
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    @SuppressWarnings("NullableProblems")
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理当前线程保存的用户数据
        UserHolder.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
